package com.itheima.commons;

import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.BeansFactory;
import org.apache.ibatis.annotations.Select;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "DecideLoginFilter", urlPatterns = "/*")
public class DecideLoginFilter implements Filter {
    private UserService userService = (UserService) BeansFactory.getBean("userService");

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String url = request.getRequestURI();
        if (url.indexOf("login.jsp") != -1 || url.indexOf("/userServlet") != -1 || url.indexOf(".css") != -1) {
            chain.doFilter(request, response);
            return;
        }

        User user = (User) request.getSession().getAttribute("user");
        System.out.println("user = " + user);
        if (user == null) {
            Cookie[] cookies = request.getCookies();
            String userName = "";
            String password = "";
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if ("userName".equals(cookie.getName())) {
                        userName = cookie.getValue();
                    }
                    if ("password".equals(cookie.getName())) {
                        password = cookie.getValue();
                    }
                }
                System.out.println("userName = " + userName);
                System.out.println("password = " + password);
                if (userName != null && userName.trim().length() > 0 && password != null && password.trim().length() > 0) {
                    user = userService.login(userName, password);
                    if (user != null) {
                        request.getSession().setAttribute("user", user);
                        chain.doFilter(request, response);
                        return;
                    }
                }
            }
        } else {
            chain.doFilter(request, response);
            return;
        }
        request.getSession().setAttribute("msg", "登录信息已过期,请重新登录");
        request.getRequestDispatcher("login.jsp").forward(request, response);
    }

    @Override
    public void destroy() {
    }

}